<?php

namespace App\Api\Three\ShopA;


/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Api\ChannelApi;

class LianTongZopAse
{
    //访问地址
    protected $appKey = ''; //系统标识
    protected $url = ''; //访问地址
    protected $secret = '';
    protected $source = '';
    protected $log = null;
    protected $appCode = null;
    protected $HMACMD5 = null;
    protected $aes  = null;
    public function __construct($appKey, $url, $secret, $source)
    {
        $this->log = new Logger('LianTongZopAse');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/LianTongZopAse.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->appCode = $appKey;
        $this->url = $url;
        $this->HMACMD5 = $secret;  //md5
        $this->aes = $source; //aes
    }
    function send($data, $method)
    {
        $url = $this->url . $method;
        // uuid
        $uuid = $this->uuid();
        // 生成时间戳
        $timestamp = $this->getTimestamp();
        $head = [
            'sign' => $this->genSign($uuid, $timestamp),
            'timestamp' => $timestamp,
            'uuid' => $uuid
        ];
        $reqObj = [
            'head' => $head,
            'body' => $data
        ];
        // var_dump($reqObj);
        $reqObj = $this->encryptAes(json_encode($reqObj), $this->aes);

        $reqParam = [
            'appCode' => $this->appCode,
            'reqObj' => $reqObj
        ];
        // var_dump($reqParam);
        $res =  $this->sendPost($url, $reqParam);
        // var_dump($res, 3333333333);
        $this->log->info('链接:' . $url . '参数:' . json_encode($data) . '返回结果:' . ($res));
        return $res;
    }
    /**
     * uuid 唯一序列码
     * @param string $prefix
     * @return string
     */
    function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-';
        $uuid .= substr($chars, 8, 4) . '-';
        $uuid .= substr($chars, 12, 4) . '-';
        $uuid .= substr($chars, 16, 4) . '-';
        $uuid .= substr($chars, 20, 12);
        return $prefix . $uuid;
    }
    //获取当前时间毫秒
    function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    // 时间戳
    function getTimestamp()
    {
        date_default_timezone_set('PRC');
        $time = $this->msectime();
        return date('Y-m-d H:i:s.') . substr($time, -3);
    }
    // 生成签名
    function genSign($uuid, $timestamp)
    {
        $dataStr = 'appCode' . $this->appCode . 'timestamp' . $timestamp . 'uuid' . $uuid . $this->HMACMD5;
        return $this->sign($this->HMACMD5, $dataStr);
    }

    /**
     * 签名
     * @param key 密钥  联通侧提供的HmacMD5
     * @param dataStr appCode+appCode值+timestamp+timestamp值*+uuid+uuid值+HmacMD5密钥值
     */
    function sign($key, $dataStr)
    {
        return base64_encode(hash_hmac("md5", $dataStr, base64_decode($key), true));
    }

    /**
     *AES加密
     */
    function encryptAes($data, $key)
    {
        $data = openssl_encrypt($data, 'aes-128-ecb', base64_decode($key), OPENSSL_RAW_DATA);
        return base64_encode($data);
    }

    function sendPost($url, $post_data)
    {
        $opt_data = json_encode($post_data);

        $header = array();
        $header[] = 'Accept:application/json';
        $header[] = 'Content-Type:application/json;charset=utf-8';
        // var_dump($url);
        // var_dump($header);
        // var_dump($opt_data);
        $curl = curl_init();  //初始化
        curl_setopt($curl, CURLOPT_URL, $url);  //设置url
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $opt_data);
        // curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        //从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //post请求
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_POST, 1);

        $result = curl_exec($curl);
        // var_dump($result);
        if ($result === false) {
            echo curl_errno($curl);
            exit();
        }

        curl_close($curl);
        return $result;
    }
}
